<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import VideoList from "./VideoList.vue";
import VideoFilter from "./VideoFilter.vue";
import {
  getMyVideosApi,
  deleteVideoApi,
  changeVideoStatusApi,
  getVideoCategoriesOptionsApi,
  updateVideoApi,
  resubmitVideoApi,
} from "@/api/video";

// 添加分类数据
const categories = ref([]);

// 获取分类列表
const loadCategories = async () => {
  try {
    const res = await getVideoCategoriesOptionsApi();
    categories.value = res || [];
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};
// 处理视频更新
const handleUpdateVideo = async (videoId, updateData) => {
  try {
    await updateVideoApi(videoId, updateData);
    ElMessage.success("视频更新成功");

    // 更新本地数据，避免重新请求
    const index = videos.value.findIndex((v) => v.video_id === videoId);
    if (index !== -1) {
      videos.value[index] = {
        ...videos.value[index],
        title: updateData.title,
        description: updateData.description,
      };
      const { value: id, label } = categories.value.find(
        (c) => c.value === updateData.categoryId
      );
      videos.value[index].category.id = String(id);
      videos.value[index].category.name = label;
    }
  } catch (error) {
    console.error("更新视频失败:", error);
    ElMessage.error("更新视频失败，请重试");
  }
};

// 视频列表数据
const videos = ref([]);
const loading = ref(false);
const total = ref(0);

// 分页参数
const pagination = reactive({
  page: 1,
  pageSize: 10,
});

// 筛选参数
const filters = reactive({
  status: "all",
  keyword: "",
});

// 加载视频列表数据
const loadVideos = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.pageSize,
      keyword: filters.keyword || undefined,
      status: filters.status === "all" ? "all" : filters.status,
    };

    const res = await getMyVideosApi(params);
    videos.value = res.data || [];
    total.value = res.pagination.total || 0;
  } catch (error) {
    console.error("加载视频列表失败:", error);
    ElMessage.error("加载视频列表失败，请重试");
  } finally {
    loading.value = false;
  }
};

// 处理筛选条件变更
const handleFilterChange = (newFilters) => {
  Object.assign(filters, newFilters);
  pagination.page = 1; // 重置页码
  loadVideos();
};

// 处理分页变更
const handlePageChange = (page) => {
  pagination.page = page;
  loadVideos();
};

// 处理每页条数变更
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.page = 1;
  loadVideos();
};

// 处理删除视频
const handleDelete = async (videoId) => {
  try {
    await ElMessageBox.confirm("确定删除该视频吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    await deleteVideoApi(videoId);

    ElMessage.success("视频删除成功");

    loadVideos(); // 重新加载列表
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除视频失败:", error);
      ElMessage.error("删除视频失败，请重试");
    }
  }
};

// 处理视频状态变更
const handleStatusChange = async (videoId, status) => {
  try {
    const statusText = status === "approved" ? "上线" : "下线";
    await ElMessageBox.confirm(
      `确定将视频${statusText}吗？`,
      `视频${statusText}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    await changeVideoStatusApi(videoId, {
      isPublic: status === "hidden" ? false : true,
    });
    ElMessage.success(`视频${statusText}成功`);

    // // 方案1: 更新本地列表状态
    // const index = videos.value.findIndex((v) => v.video_id === videoId);
    // if (index !== -1) {
    //   console.log(" videos.value[index]:",  videos.value[index]);
    //   videos.value[index].status = status;
    // } else {
    //   // 如果找不到对应视频，重新加载整个列表
    //   await loadVideos();
    // }

    // 方案2: 直接重新加载整个列表，确保数据一致性
    await loadVideos();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除视频失败:", error);
      ElMessage.error("删除视频失败，请重试");
    }
  }
};

// 重新提交审核
const handleResubmit = async (videoId) => {
  try {
    await ElMessageBox.confirm(
      "确定重新提交此视频进行审核吗？",
      "重新提交审核",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );
    await resubmitVideoApi(videoId);
    ElMessage.success("视频已重新提交审核");

    // // 更新本地列表状态
    // const index = videos.value.findIndex((v) => v.id === videoId);
    // if (index !== -1) {
    //   videos.value[index].status = "pending";
    // }
    // 方案2: 直接重新加载整个列表，确保数据一致性
    await loadVideos();
  } catch (error) {
    if (error !== "cancel") {
      console.error("重新提交视频失败:", error);
      ElMessage.error("操作失败，请重试");
    }
  }
};

// 初始加载
onMounted(() => {
  loadVideos();
  loadCategories();
});
</script>

<template>
  <div class="manage-container">
    <h2 class="section-title">视频管理</h2>

    <!-- 筛选区域 -->
    <VideoFilter :filters="filters" @filter-change="handleFilterChange" />

    <!-- 视频列表 -->
    <VideoList
      :videos="videos"
      :loading="loading"
      :categories="categories"
      @delete="handleDelete"
      @status-change="handleStatusChange"
      @update="handleUpdateVideo"
      @resubmit="handleResubmit"
    />

    <!-- 分页 -->
    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.manage-container {
  padding: 0 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 24px;
  color: white;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-state {
  margin-top: 60px;
}
</style>
